﻿using System.IO;

namespace GoodStuff.Text
{
    /// <summary>
    /// Generates a so-called Comma Separated Values file, with a configurable separator.
    /// </summary>
    public class CSVStreamWriter
    {
        /// <summary>
        /// Gets the separator that separates the columns of the output
        /// </summary>
        public string Separator { get; private set; }
        private TextWriter _stream;
        private bool _firstInLine;

        /// <summary>
        /// Construct a new CSVStreamWriter
        /// </summary>
        /// <param name="stream">The stream used to write the actual contents</param>
        /// <param name="separator">The separator to be used</param>
        public CSVStreamWriter(TextWriter stream, string separator)
        {
            _stream = stream;
            Separator = separator;
            _firstInLine = true;
        }

        /// <summary>
        /// Returns the internal stream used for debugging only.
        /// </summary>
        /// <returns></returns>
        public string toString()
        {
            return "wtf" + _stream.ToString();
        }

        /// <summary>
        /// Writes a numeric value to the output stream
        /// </summary>
        /// <param name="value">The value to write</param>
        public void Write(int value)
        {
            this.Write(value.ToString());
        }

        /// <summary>
        /// Writes a stringvalue to the output stream
        /// </summary>
        /// <param name="value">the value to write</param>
        /// <remarks>If the value to be written contains the separator string, the value is escaped with quotes. Any quotes already 
        /// in the value, will be doubled.</remarks>
        public void Write(string value)
        {
            if (value == null)
            {
                value = string.Empty;
            }
            if (value.Contains(Separator))
            {
                //replace quotes to double quotes and surrond them with quotes.
                value = string.Concat("\"", value.Replace("\"", "\"\""), "\"");
            }

            if (!_firstInLine)
            {
                _stream.Write(Separator);                
            }
            _stream.Write(value);

            _firstInLine = false;
        }

        /// <summary>
        /// Ends the current line and starts a new one.
        /// </summary>
        public void WriteLine()
        {
            _firstInLine = true;
            _stream.WriteLine();
        }

        /// <summary>
        /// Write and empty value to the output. Equivalent to Write(string.Empty)
        /// </summary>
        internal void WriteEmpty()
        {
            Write(string.Empty);
        }
    }
}
